package analysis;

import common.AnalysisWare;
import common.Constants;
import common.DataAnalysis;
import redis.clients.jedis.Tuple;
import util.FileUtil;
import util.remote.RemoteConnectResult;

import java.util.*;

/**
 * Created by J.Chen on 2017/5/26.
 */
@AnalysisWare(confCode = "RANK_DATA", desc = "榜单数据查询")
public class RankDataAnalysis extends DataAnalysis {
    public final String ZuserRankTopPop = "zuser_rank:top_pop";

    /**
     * 排行榜 - 财富top30
     */
    public final String ZuserRankTopFortune = "zuser_rank:top_fortune";
    public final String ZuserRankTopGuizu = "zuser_rank:top_fortune";

    private String monthKey(Calendar calendar) {

        return String.format("zAristocratic:rank:month:%d",
                calendar.get(Calendar.YEAR) * 100 + calendar.get(Calendar.MONTH));
    }

    public RankDataAnalysis(RemoteConnectResult result, String confCode) {
        super(result, confCode);
    }

    @Override
    public void execute() {
        ex(ZuserRankTopPop, "人气");
        ex(ZuserRankTopFortune, "财富");
        Calendar calendar = Calendar.getInstance();
        calendar.set(2017, 3, 1);
        ex(monthKey(calendar), "贵族");
        String sql = "select * from user_info__%d ";
        List<Map<String, String>> ret = new ArrayList<>();
        for (int i = 0; i < 64; i++) {
            List<Map<String, String>> list = result.getMysqlUtil().selectList(String.format(sql, i));
            ret.addAll(list);
        }
        ret.sort(Comparator.comparingInt(s -> -Integer.parseInt(s.get("lv_exp"))));
        FileUtil fileUtilLv = new FileUtil(Constants.getActOutputDir(result.getRemoteConf(), "等级"));
        for (int i = 0; i < Math.min(30, ret.size()); i++) {
            Map<String, String> m = ret.get(i);
            fileUtilLv.writeln("|", m.get("user_id"), m.get("sex"), m.get("lv_exp"));
        }
        fileUtilLv.close();

    }

    private void ex(String key, String name) {
        FileUtil fileUtilPop = new FileUtil(Constants.getActOutputDir(result.getRemoteConf(), name + "排行榜"));
        for (Tuple t : result.getRedisUtil().zrevrangeWithScores(key, 0, 29)) {
            String sex = result.getRedisUtil().hget("muser_info:" + t.getElement(), "sex");
            fileUtilPop.writeln("|", t.getElement(), sex, "" + t.getScore());
        }

        fileUtilPop.close();
    }
}
